package erp_services

import (
	"fmt"
	"log"
	"plugin"
	"xiehui-service/app/models/erp_models"
	"xiehui-service/app/services/types"
	"xiehui-service/global"
)

type orderAutoDispatchPlanService struct {
}

var OrderAutoDispatchPlanService = new(orderAutoDispatchPlanService)

// 保存自动调度计划
func (orderAutoDispatchPlanService *orderAutoDispatchPlanService) SavePlan(planItems []erp_models.OrderAutoDispatchPlan) (err error) {
	err = global.App.DB.CreateInBatches(&planItems, 500).Error
	if err != nil {
		return err
	}
	return
}

// 取消当前调度计划
func (orderAutoDispatchPlanService *orderAutoDispatchPlanService) CancelPlan() (canclPlan []erp_models.OrderAutoDispatchPlan, err error) {
	canclPlan, err = OrderAutoDispatchPlanService.GetCurrentPlan()
	if err != nil {
		return canclPlan, err
	}

	err = global.App.DB.Model(&canclPlan).Updates(map[string]interface{}{"current": 0}).Error
	if err != nil {
		return canclPlan, err
	}

	return
}

// 获取当前调度计划
func (orderAutoDispatchPlanService *orderAutoDispatchPlanService) GetCurrentPlan() (currentPlan []erp_models.OrderAutoDispatchPlan, err error) {
	err = global.App.DB.Find(&currentPlan, "current = ?", 1).Error
	if err != nil {
		return currentPlan, err
	}
	return
}

// 生成自动调度计划
func (orderAutoDispatchPlanService *orderAutoDispatchPlanService) GenerateSDPlan() {
	orderTask, err := OrderTaskService.GetAutoOrderTask()
	if err != nil {
		log.Print(err)
		return
	}

	if len(orderTask) == 0 {
		log.Print("无满足条件的任务单数据")
		return
	}

	p, err := plugin.Open("app/plugin/plugin.so")
	if err != nil {
		global.App.Log.Error(err.Error())
		return
	}
	sym, err := p.Lookup("NewPlugin")
	if err != nil {
		global.App.Log.Error(err.Error())
		return
	}

	newFunc, ok := sym.(func() interface{})
	if !ok {
		global.App.Log.Error("无法将 Plugin 符号转换为接口类型")
		return
	}

	sdPlugin, ok := newFunc().(types.SDInterface)
	if !ok {
		global.App.Log.Error("无法将 newFunc 转换为函数类型")
		return
	}

	sdPlan, _ := sdPlugin.GenerateSDPlan(orderTask)

	_, e := OrderAutoDispatchPlanService.CancelPlan()
	if e != nil {
		log.Println(e)
	}

	e = OrderAutoDispatchPlanService.SavePlan(sdPlan)
	if e != nil {
		log.Println(e)
	}
}

// 更新调度计划状态
func (orderAutoDispatchPlanService *orderAutoDispatchPlanService) SetPlanState(plan_id int, state int) (thisPlan erp_models.OrderAutoDispatchPlan, err error) {
	err = global.App.DB.First(&thisPlan, plan_id).Updates(map[string]interface{}{"state": state}).Error

	if err != nil {
		err = fmt.Errorf("更新计划状态失败:%s", err)
	}

	return
}
